package easy;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by daodao on 2017/11/30.
 * Problem 13
 * Description: Given a roman numeral, convert it to an integer.
 * Input is guaranteed to be within the range from 1 to 3999.
 */
public class RomanToInteger {
    public static int romanToInt(String s) {
        Map<Character, Integer> romanMap = new HashMap<>();
        romanMap.put('I', 1);
        romanMap.put('X', 10);
        romanMap.put('C', 100);
        romanMap.put('M', 1000);
        romanMap.put('V', 5);
        romanMap.put('L', 50);
        romanMap.put('D', 500);
        int result = 0;
        char[] chars = s.trim().toCharArray();
        int len = chars.length;
        if (len == 1) {
            if (romanMap.containsKey(chars[0])) {
                return romanMap.get(chars[0]);
            }
        }
        int i;
        for (i = chars.length - 1; i > 0; i--) {
            if (romanMap.containsKey(chars[i])) {
                result += romanMap.get(chars[i]);
                // 小的数字在大的数字的左边，所表示的数等于大数减小数得到的数，如IV=4，IX=9
                if (romanMap.get(chars[i - 1]) < romanMap.get(chars[i])) {
                    result -= romanMap.get(chars[i - 1]);
                    i--;
                }
            }
        }
        if (i == 0 && romanMap.containsKey(chars[i])) {
            result += romanMap.get(chars[0]);
        }
        return result;
    }
}
